package com.example.filefusion.service;

import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.StatObjectArgs;
import io.minio.StatObjectResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
public class DownloadService {

    private static final Logger logger = LoggerFactory.getLogger(DownloadService.class);

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;

    /**
     * 获取文件流用于断点续传下载
     * @param filename 文件名
     * @param startRange 开始字节位置
     * @param endRange 结束字节位置
     * @return 文件输入流
     * @throws Exception 异常
     */
    public InputStream downloadChunk(String filename, long start, long end) throws Exception {
        logger.info("开始下载文件片段: filename={}, range={} - {}", filename, start, end);
        InputStream inputStream = minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(filename)
                        .offset(start)
                        .length(end - start + 1)
                        .build()
        );
        logger.info("文件片段下载准备完成: filename={}, range={} - {}", filename, start, end);
        return inputStream;
    }

    /**
     * 获取文件大小
     * @param filename 文件名
     * @return 文件大小
     * @throws Exception 异常
     */
    public long getFileSize(String filename) throws Exception {
        logger.info("开始获取文件大小: filename={}", filename);
        StatObjectResponse stat = minioClient.statObject(
                StatObjectArgs.builder()
                        .bucket(bucketName)
                        .object(filename)
                        .build()
        );
        long fileSize = stat.size();
        logger.info("文件大小获取完成: filename={}, size={}", filename, fileSize);
        return fileSize;
    }
}